package uz.rt.dicom.io;

import uz.rt.dicom.data.DataSet;
import uz.rt.dicom.data.IDataElement;
import uz.rt.dicom.data.MetaInformation;
import uz.rt.dicom.dictionary.DicomDictionary;

import java.io.*;

public class DicomReader
{
// ------------------------------ FIELDS ------------------------------

    private String filename;
    private DataSet dataSet;
    private DicomInputStream dicomInputStream = null;
    private MetaInformation metaInformation = null;

// --------------------------- CONSTRUCTORS ---------------------------

    public DicomReader(String filename)
    {
        setFilename(filename);
        dataSet = new DataSet();
    }

// --------------------- GETTER / SETTER METHODS ---------------------

    public DataSet getDataSet()
    {
        return dataSet;
    }

    public synchronized String getFilename()
    {
        return filename;
    }

    public synchronized void setFilename(String filename)
    {
        this.filename = filename;
    }

    public MetaInformation getMetaInformation()
    {
        return metaInformation;
    }

// -------------------------- OTHER METHODS --------------------------

    public synchronized void read() throws IOException
    {
        File file = new File(filename);
        if (!file.exists())
            throw new IOException("File (" + file + ") does not exist.");
        if (!file.isFile())
            throw new IOException("Filename is not a file (" + file + ").");
        //dicomInputStream = new DicomInputStream(new FileInputStream(file));
        dicomInputStream = new DicomInputStream(new BufferedInputStream(new FileInputStream(file)));
        if (!dicomInputStream.markSupported())
            throw new IOException("Dicom input stream should support a mark inorder to determine the " +
                                          "meta information presence.");
        dicomInputStream.mark(133);
        if (readMetaInformation() == -1)
            dicomInputStream.reset();
        dicomInputStream.setDictionary(DicomDictionary.getInstance());
        try
        {
            while (!dicomInputStream.endOfStream())
            {
                IDataElement element;
                element = dicomInputStream.readElement();
                dataSet.add(element);
            }
        }
        catch (EOFException eofException)
        {
            System.err.println("Reached the end of the dicom stream.");
        } finally
        {
            dicomInputStream.close();
        }
    }

    private synchronized int readMetaInformation() throws IOException
    {
        if (metaInformation == null)
            metaInformation = new MetaInformation();
        metaInformation.clear();
        return metaInformation.read(dicomInputStream);
    }
}
